﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.User;
using Provenance.Read.Api.Application.Command.User;
using Provenance.Read.Api.Dto.User;

namespace Provenance.Read.Api.Application.CommandHandler.User
{
    public class BackUserCommandHandler : IRequestHandler<BackUserCommand, ApiResult<BackUserCommandResponseDTO>>
    {
        private readonly IUserInfoRepository _userInfoRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly ILogger<BackUserCommandHandler> _logger;
        private readonly IMapper _mapper;
        public BackUserCommandHandler(IUserInfoRepository userInfoRepository, IUserRoleRepository userRoleRepository, IRoleRepository roleRepository, ILogger<BackUserCommandHandler> logger, IMapper mapper)
        {
            _userInfoRepository = userInfoRepository;
            _userRoleRepository = userRoleRepository;
            _roleRepository = roleRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<BackUserCommandResponseDTO>> Handle(BackUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _userInfoRepository.GetAsync(x => x.UserId == request.UserId && x.IsDeleted == false);
                if (obj == null)
                {
                    return ApiResult<BackUserCommandResponseDTO>.Failure("User not found");
                }
                var result = _mapper.Map<BackUserCommandResponseDTO>(obj);
                //反填一个用户对应的所有角色ID 
                var roleList = await _userRoleRepository.GetAllAsync(x => x.UserId == request.UserId&&x.IsDeleted==false);
                result.RoleIds = string.Join(',', roleList.Select(x => x.RoleId).ToArray());
                return ApiResult<BackUserCommandResponseDTO>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "BackUserCommandHandler Error: " + ex.Message);
                return ApiResult<BackUserCommandResponseDTO>.Failure(ex.Message);
            }
        }
    }
}
